<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="divport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<title></title>
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.5/lib/index.css">
		<link rel="stylesheet" href="/statics/wxdemo/css/chatpage.css">
		<script src="/statics/wxdemo/js/flexble.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
		<script src="https://cdn.jsdelivr.net/npm/vant@2.5/lib/vant.min.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/js/jquery-1.9.1.min.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/sdk/webimSDK3.1.2.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/js/WebIMConfig.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/js/webconn.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/utils/dialog.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/js/localstorage.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/utils/getMsgData.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/utils/msgtype.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/utils/login.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/utils/record_status.js"></script>
		<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
		<script type="text/javascript" src="/statics/wxdemo/sdk/vconsole.min.js"></script>
	</head>
	<body>
		<div class="chatPageBox" id="bigbox">
			<div>
				<div class="fixedtop">
					<div class="getBack">
						<van-button class="arrowbox" type="default" @click="back">
							<img src="/statics/wxdemo/img/back.png">
						</van-button>
						<p>{{sendConfig.name}}</p>
						<!-- <van-button class="dingdan" type="default" @click="gourl('friendSet.html')">
							<img class="oicon1" src="/statics/wxdemo/img/oicon1.png">
						</van-button> -->
					</div>
				</div>
				<div
				scroll-y="true"
				class="wrap"
				upper-threshold='-50'
			    >
					<div class="message" v-for="(item,index) in txtlist" :key="item">
						<div :class="item.self?'self':'main'">
							<div class="user">
								<span v-if="!item.self" class="user-text">{{item.from}}</span>
								<span v-if="item.self" class="user-text">{{name}}</span>
							</div>
							<img class="avatar" src="/statics/wxdemo/img/avatar.jpg"/>
							<div class="msg">
								<img v-if="!item.self" src="/statics/wxdemo/img/popleftarrow@2x.png" class="msg_popleftarrow"/>
								<img v-if="item.self" src="/statics/wxdemo/img/poprightarrow@2x.png" class="msg_poprightarrow"/>
								<span v-if="item.type == 'txt' || item.type == 'emoji'" class="msginnerbox" v-for="(valitem,valindex) in item.value" :key="valindex">
								<span v-if="valitem.type == 'txt'">{{valitem.data}}</span>
								<img v-if="valitem.type == 'emoji'" class="emojiitem2" :src="emojiList.path+valitem.data" ></img>
								</span>
								
								<img v-if="item.type == 'img'" class="imgitem" :src="item.value" mode="aspectFill" @click="preimg(item)">
								<audio-msg
									v-if="item.type == 'audio'"
									:msg="item"></audio-msg>
							</div> 
							</div>
						</div>
				</div>
				<div class="room_bar">
					<div class="text-input">
						<textarea
							class="f news"
							type="text"
							v-model="value"
							cursor-spacing="65"
							confirm-type="send"
							placeholder-style="color:#CFCFCF; padding-left:5px;"
						>
							
						</textarea> 
						<div :class="[{nosendbtn:!cansend},'sendbtn']" @click="sendtext">发送</div>
					</div>
					<div class="menuList">
						<div class="menuinner">
							<img class="Emoji" src="/statics/wxdemo/img/emoji.png" @click="showemoji = true">
							<div class="picbtnbox">
								<img class="picbtn" src="/statics/wxdemo/img/picb.png">
								<input type="file" id="fileinp" value=""  @change="sendimg" accept="image/*"/>
							</div>
							<!-- <img class="camerabtn" src="/statics/wxdemo/img/xji.png"> -->
							<img class="camerabtn" src="/statics/wxdemo/img/file.png">
							<img class="audiobtn" src="/statics/wxdemo/img/audiop.png" @click="openrecordbox">
							<!-- <p @click="record">录制</p> -->
							<!-- <p @click="play">播放</p> -->
						</div>
					</div>
					<scroll-div v-if="showemoji" :class="[{scrollup:showemoji,scrolldown:!showemoji},'scrolldiv']" scroll-y="true">
						<div class="emojibox">
							<img 
							class="emojiitem" 
							:src="emojiList.path+emojitem" 
							v-for="(emojitem,index) in emojiList.map"
							:key="index"
							@click="tapemoji(emojitem)"
							>
							<div class="emojidel">
								<img src="/statics/wxdemo/img/faces/btn_del.png">
							</div>
						</div>
					</scroll-div>	
				</div>
				
						
				<div v-if="showrecordpop" class="modal modal-record">
					<div class="recordcover" @click="hiderecordbox"></div>
					<div class="modal-body">
						<div class="sound-waves">
							<div v-for="item in radomheight" :key="item" :style="{height:item+'px',marginTop:-item/2+'px'}"></div>
							<div style='clear:both;width:0;height:0;'></div>
						</div>
						<span class="desc">{{ RecordDesc[recordStatus] }}</span>
						<button class="dot" @touchstart="handleRecording" @touchmove="handleRecordingMove" @touchend="handleRecordingCancel"
						 @touchcancel="handleRecordingCancel">
							<img class="icon-mic" src="/statics/wxdemo/img/send.png" />
						</button>
					</div>
				</div>
			</div>
			
			
		</div>
	</body>
</html>
<script type="text/javascript">
	//录音=》停止，获取localId =》上传微信服务器获得serverId=》下载地址到环信服务器=》播放
WebIM.message = WebIM.default.message;
const InitHeight = [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50];
var webvue = new Vue({
	el: '#bigbox',
	data() {
		return {
			value:'',
			cansend:false,
			showemoji:false,
			emojiList:getemoji(),//表情数据
			txtlist:getDialog(),//对话数据
			sendConfig:'',//对方好友或群的id，名字
			isgroup:false,//是否是群
			type:'',//
			name:'',//自己的id
			showrecordpop:false,
			recordStatus:RecordStatus_().HIDE, 
			RecordStatus:RecordStatus_(),
			RecordDesc:RecordDesc_(),		// 模板中有引用
			radomheight: InitHeight,
			wxconfig:'',
		}
	},
	mounted(){
		console.log(this.RecordStatus.SHOW)
		isfirst = 3;
		relogin()
		this.name = getStorage('myid');
		if(getStorage('pagedata')){
			this.sendConfig = getStorage('pagedata');
			console.log(this.sendConfig)
			saveStorage('pagedata','')
		}
		if(getStorage('chatype')){
			this.isgroup = true;
			console.log(this.type)
			removeStorage('chatype')
		}else{
			this.isgroup = false;
		}
		this.ajfunc()
	},
	watch:{
		value:{
			handler(){
				if(this.value){
					this.cansend = true;
				}else{
					this.cansend = false;
				}
			}
		}
	},
	methods:{
		ajfunc(){
			var that = this;		
			wx.config({
			  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			  appId: '<?= $signPackage["appId"];?>', // 必填，公众号的唯一标识
			  timestamp: <?= $signPackage["timestamp"];?>, // 必填，生成签名的时间戳
			  nonceStr: '<?= $signPackage["nonceStr"];?>', // 必填，生成签名的随机串
			  signature: '<?= $signPackage["signature"];?>',// 必填，签名
			  jsApiList: ['startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice'] // 必填，需要使用的JS接口列表
			});
				
		},
		resetscroll(){
			var clientHeight =  document.body.clientHeight;
			var topHeight = $('.fixedtop').outerHeight(true);
			var room_barHeight = $('.room_bar').outerHeight(true);
			var height = clientHeight - topHeight - room_barHeight - 20;
			$(".wrap").css({'height':height+'px'});
		},
		back(){
			window.location.href = 'chatlist.html';
		},
		gourl(url){
			window.location.href = url;
		},
		scrolllistbox(){
			console.log('滚动')
			var clientHeight =  document.body.clientHeight;
			var topHeight = $('.fixedtop').outerHeight(true);
			var room_barHeight = $('.room_bar').outerHeight(true);
			var height = clientHeight - topHeight - room_barHeight - 20;
			$(".wrap").css({'height':height+'px'});
			console.log($(".wrap").height())
			$(".wrap").animate({scrollTop:$(".wrap").prop("scrollHeight")})
		},
		sendtext(){
			// var that = this;
			// var id = conn.getUniqueId();                 // 生成本地消息id
			// var msg = new WebIM.message('custom', id);   // 创建自定义消息
			// var customEvent = "customEvent";             // 创建自定义事件
			// var customExts = {
			// 	record:'record',
			// 	url:'issss'
			// };                         // 消息内容，key/value 需要 string 类型
			// msg.set({
			// 	from:that.name,
			// 	to: that.sendConfig.sendID,                          // 接收消息对象（用户id）
			// 	customEvent,
			// 	customExts,
			// 	ext:{},                                  // 消息扩展
			// 	roomType: false,
			// 	success: function (id, serverMsgId) {},
			// 	fail: function(e){}
			// });
			// conn.send(msg.body);
			// return
			var that = this;
			var ext = {};
			if(this.isgroup){
				sendID = this.groupid
				ext = {
					groupname:this.sendConfig.name
				}
			}else{
				sendID = this.sendID
			}
			// return
			if(that.value != ''){
				var id = conn.getUniqueId();                 // 生成本地消息id
				var msg = new WebIM.message('txt', id);      // 创建文本消息
				var option = {
					msg: that.value,                  // 消息内容
					from:that.name,
					to: that.sendConfig.sendID,                          // 接收消息对象（用户id）
					roomType: false,
					ext: ext,                                  //扩展消息
					success: function (id, serverMsgId) {
						console.log('send private text Success');  
					},                                       // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
					fail: function(e){
						console.log("Send private text error");  
					}                                        // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
				};
				msg.set(option);
				console.log(this.type)
				if(this.isgroup){
					console.log("群群群2")
					msg.setGroup('groupchat');
				}
				let msgData = {
					self:true,
					type:msgtype().TEXT,
					value:this.value,
					from:msg.body.from,
					to:msg.body.to
				}
				pushDialog(getMsgData(msgData,msgtype().TEXT))
				this.value = '';
				console.log(getDialog())
				console.log(msg)
				conn.send(msg.body);
				setTimeout(()=>{
					this.scrolllistbox()
				},300)
			}	
		},
		sendimg(){
			console.log('发图了')
			var that = this;
			var id = conn.getUniqueId();                   // 生成本地消息id
			var msg = new WebIM.default.message('img', id);        // 创建图片消息
			var input = document.getElementById('fileinp');  // 选择图片的input
			var file = WebIM.default.utils.getFileUrl(input);      // 将图片转化为二进制文件
			var sendID,ext = {};
			if(this.isgroup){
				sendID = this.groupid
				ext = {
					groupname:this.sendConfig.name
				}
			}else{
				sendID = this.sendID
			}
			var allowType = {
			    'jpg': true,
			    'gif': true,
			    'png': true,
			    'bmp': true
			};
			if (file.filetype.toLowerCase() in allowType) {
			    var option = {
			        apiUrl: WebIM.config.apiURL,
			        file: file,
			        from:that.name,
			        to: that.sendConfig.sendID, 
			        ext: ext,           // 接收消息对象
			        roomType: false,
			        chatType: 'singleChat',
			        onFileUploadError: function () {      // 消息上传失败
			            console.log('onFileUploadError');
			        },
			        onFileUploadComplete: function () {   // 消息上传成功
			            console.log('onFileUploadComplete');
			        },
			        success: function () {                // 消息发送成功
			            console.log('Success');
			        },
			        flashUpload: WebIM.flashUpload
			    };
			    msg.set(option);
				if(this.isgroup){
					console.log("群群群2")
					msg.setGroup('groupchat');
				}
			    conn.send(msg.body);
				let msgData = {
					self:true,
					type:msgtype().IMAGE,
					value:msg.value.url,
					valuearr:[msg.value.url],
					from:msg.body.from,
					to:msg.body.to
				}
				pushDialog(msgData)
				console.log(getDialog())
				console.log(msg)
				this.scrolllistbox()
			}
		},
		preimg(item){
			console.log(item)
			vant.ImagePreview({
			  images: [item.value],
			  showIndex:false
			});
		},
		tapemoji(emoji){
			let emojival;
			for(var key in this.emojiList.map){
				if(this.emojiList.map[key] == emoji){
					emojival = key
				}
				// console.log(key); 
			}
			if(this.value){
				this.value = this.value+emojival
			}else{
				this.value = emojival
			}
		},
		handleRecording(e){
			wx.startRecord();
			return
			var promise = navigator.mediaDevices.getUserMedia({
				audio: true
			 });
			 promise.then(function(stream) {
				alert(stream)
		
				recorder.ondataavailable = function() {
				  //收集媒体设备 获得到的 可以使用的 媒体流数据
				  console.log(event.data)
				}
			 });
		
			 promise.catch(function(error) {
				  alert(error.name)
				  alert(error.message)
			 });
			return
			let me = this;
			this.recordClicked = true;
		    setTimeout(() => {
		      	if (this.recordClicked == true) {
		        	executeRecord()
		      	}
		    }, 350)
		    function executeRecord(){
				// #ifdef APP-PLUS
				startRecord()
				return;
				// #endif
				
			    uni.getSetting({ 
			      	success: (res) => {
				        let recordAuth = res.authSetting['scope.record']
				        if (recordAuth == false) { //已申请过授权，但是用户拒绝
				          	uni.openSetting({
					            success: function (res) {
					              let recordAuth = res.authSetting['scope.record']
					              if (recordAuth == true) {
					                uni.showToast({
							        	title: "授权成功",
							        	icon: "success"
							        })
					              } else {
					                uni.showToast({
							        	title: "请授权录音",
							        	icon: "none"
							        })
					              }
								  me.isLongPress = false;
					            }
				          	})
				        } else if (recordAuth == true) { // 用户已经同意授权
				          	startRecord()
				        } else { // 第一次进来，未发起授权
					        uni.authorize({
					            scope: 'scope.record',
					            success: () => {//授权成功
					              	uni.showToast({
							        	title: "授权成功",
							        	icon: "success"
							        })
					            }
					        })
				        }
				    },
				    fail: function () {
				        uni.showToast({
				        	title: "鉴权失败，请重试",
				        	icon: "none"
				        })
			      	}
			    })
		    }
		
			function startRecord(){
				me.changedTouches = e.touches[0];
				me.recordStatus = me.RecordStatus.HOLD;
				RunAnimation = true;
				me.myradom();
		
				let recorderManager = me.recorderManager || uni.getRecorderManager();
				recorderManager.onStart(() => {
					// console.log("开始录音...");
				});
				recorderManager.start({
					format: "mp3"
				});
				// 超时
				setTimeout(function(){
					me.handleRecordingCancel();
					RunAnimation = false
				}, 100000);
			}
		},
		myradom(){
		    const that = this;
		    var _radomheight = that.radomheight;
		    for (var i = 0; i < that.radomheight.length; i++) {
		      //+1是为了避免为0
		     _radomheight[i] = (100 * Math.random().toFixed(2))+10;
		    }
			that.radomheight = _radomheight
		    if (RunAnimation) {
		    	setTimeout(function () {that.myradom(); }, 500);
		    }else{
		    	return
		    }
		},
		handleRecordingMove(e){
			var touches = e.touches[0];
			var changedTouches = this.changedTouches;
			if(!changedTouches){
				return;
			}
		
			if(this.recordStatus == this.RecordStatus.SWIPE){
				if(changedTouches.pageY - touches.pageY < 20){
					this.recordStatus = this.RecordStatus.HOLD
				}
			}
			if(this.recordStatus == this.RecordStatus.HOLD){
				if(changedTouches.pageY - touches.pageY > 20){
					this.recordStatus = this.RecordStatus.SWIPE
				}
			}
		},
		handleRecordingCancel(){
			RunAnimation = false
			let recorderManager = this.recorderManager;
			// 向上滑动状态停止：取消录音发放
			if(this.recordStatus == this.RecordStatus.SWIPE){
				this.recordStatus = this.RecordStatus.RELEASE
			}
			else{
				this.recordStatus = this.RecordStatus.HIDE;
				this.recordClicked = false;
			}
		
			recorderManager.onStop((res) => {
				console.log('结束录音')
				// console.log("结束录音...", res);
				if(this.recordStatus == this.RecordStatus.RELEASE){
					console.log("user canceled");
					this.recordStatus = this.RecordStatus.HIDE
					return;
				}
				if (res.duration < 1000) {
			        wx.showToast({
			        	title: "录音时间太短",
			        	icon: "none"
			        })
			    } else {
			        // 上传
					this.uploadRecord(res.tempFilePath, res.duration);
					console.log('上传')
					this.showrecordpop = false;
			    }
				this.recordStatus = this.RecordStatus.HIDE;
			});
			// 停止录音
			recorderManager.stop();
			this.showrecordpop = false;
			console.log('停止录音')
		},
		uploadRecord(tempFilePath, dur){
			var str = WebIM.config.appkey.split("#");
			var me = this;
			var token = WebIM.conn.context.accessToken;
			uni.uploadFile({
				url: "https://a1.easemob.com/" + str[0] + "/" + str[1] + "/chatfiles",
				filePath: tempFilePath,
				name: "file",
				header: {
					"Content-Type": "multipart/form-data",
					Authorization: "Bearer " + token
				},
				success(res){
					// 发送 xmpp 消息
					var id = WebIM.conn.getUniqueId();
					var msg = new WebIM.message(msgType.AUDIO, id);
					var dataObj = JSON.parse(res.data);
					// 接收消息对象
					msg.set({
						apiUrl: WebIM.config.apiURL,
						accessToken: token,
						body: {
							type: msgType.AUDIO,
							url: dataObj.uri + "/" + dataObj.entities[0].uuid,
							filetype: "",
							filename: tempFilePath,
							accessToken: token,
							length: Math.ceil(dur / 1000)
						},
						from: me.from,
						to: me.to,
						roomType: false,
						chatType: msgType.chatType.SINGLE_CHAT,
						success: function (argument) {
							disp.fire('em.chat.sendSuccess', id);
						}
					});
					// if(me.isGroupChat()){
					// 	msg.setGroup("groupchat");
					// }
					
					msg.body.length = Math.ceil(dur / 1000);
					
					//console.log('发送的语音消息', msg.body)					 
					let obj = {
						self:true,
						id:msgType.AUDIO+msg.id,
						type:msgType.AUDIO,
						value:getMsgData(msg,msgType.AUDIO),
						body:msg.body.body
					}
					WebIM.conn.send(msg.body);
					console.log(msg)
					// console.log(getMsgData(msg,msgType.IMAGE))
					me.$store.dispatch('pushMsg',obj)
					console.log(me.$store.state.msgList)
				}
			});
		},
		openrecordbox(){
			this.showrecordpop = true;
			this.recordStatus = this.RecordStatus.SHOW;
		},
		hiderecordbox(){
			this.showrecordpop = false;
			this.recordStatus = this.RecordStatus.HIDE;
		},
		record(){
			
		}
	}
})
window.addEventListener('focusout', function() {
    window.scrollTo(0, 0)
 })

$(document).ready(function(){
	
	$("textarea").focus(function(){
		console.log('focus')
		setTimeout(()=>{
			console.log('呱呱')
			webvue.scrolllistbox()
		},300)
	});
	$("textarea").blur(function(){
		console.log('blur')
		setTimeout(()=>{
			console.log('呱呱')
			webvue.scrolllistbox()
		},300)
	});
});
</script>